<!--
 * @Author: Nico
-->
<template>
  <UiPdaFormItem :class="{ hidden: info.extension.hidden.value }" :info="info">
    <div
      class="mr-1 mt-0"
      :style="{
        padding: `${info.extension.paddingTop.value}px ${info.extension.paddingRight.value}px ${info.extension.paddingBottom.value}px ${info.extension.paddingLeft.value}px`,
      }"
    >
      <van-field
        :ref="info._id"
        v-model.trim="formDataModelLabel"
        v-ui-ref="vSetRef"
        class="border-b-2 rounded-none uiPdaSelect"
        readonly
        type="text"
      >
        <template #input>
          <text v-if="info.extension.extendRule.value.required && info.extension.extendRule.value.ChangeSwitch" style="color: red">*</text>
          <van-uploader
            :ref="info._id"
            v-model="fileList"
            v-ui-ref="vSetRef"
            :accept="info.extension.accept.value"
            :after-read="afterRead"
            capture="camera"
            :disabled="info.extension.disabled.value"
            :max-count="info.extension.maxCount.value"
            multiple
            name="uploadFile"
            :preview-size="info.extension.size.value + 'px'"
            @delect="delect"
          >
            <template #preview-cover="{ file }">
              <div class="preview-cover van-ellipsis">{{ file.name }}</div>
            </template>
          </van-uploader>
        </template>
      </van-field>

      <!-- <div v-if="!info.extension.autoUpload.value"><van-button size="small" type="primary" @click="uploader">上传</van-button></div> -->
    </div>
  </UiPdaFormItem>
</template>
<script>
  import { defineComponent } from 'vue'
  import { Uploader, Button, Field } from 'vant'
  import { UiMixin, ElementsFormMixin, RefsInjectMixin } from '@ve/mixin'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import isArray from 'lodash/isArray'
  import { Toast } from 'vant'
  import { processingConstant, replaseRegVariable } from '@ve/utils/utils'
  export default defineComponent({
    name: 'UiPdaUpload',
    components: { [Uploader.name]: Uploader, [Button.name]: Button, [Field.name]: Field },
    mixins: [UiMixin, ElementsFormMixin, RefsInjectMixin],
    data() {
      return {
        formDataModelLabel: '',
        fileList: [],
        requestData: {}, //请求参数
        requestList: {}, //上传参数列表
      }
    },
    computed: {
      vmRequestData() {
        return this.info.extension.requestData
      },
    },
    watch: {
      fileList(value) {
        console.log('fileList变化', value)
        this.setFormData()
      },
    },

    mounted() {},
    methods: {
      delect(file) {
        console.log('delect=====file', file)
      },
      afterRead(file) {
        this.requestList = {}
        // 判断是不是同时选了多个文件
        if (isArray(file)) {
          file.forEach((item) => {
            this.setFormData(item)
          })
        } else {
          this.setFormData(file)
        }
        // if (this.info.extension.autoUpload.value) {
        //   this.uploader()
        // }
      },
      setFormData() {
        let formData = new FormData()
        const arr = this.fileList.map((v) => {
          return v.file
        })
        if (arr.length === 0) {
          this.requestList = {}
          return
        }
        console.log('file', this.fileList, arr)
        // formData.append('uploadFile', arr)
        for (var i = 0; i < arr.length; i++) {
          formData.append('uploadFile', arr[i])
        }
        let _data = {}
        if (this.vmRequestData.value && isArray(this.vmRequestData.value)) {
          this.vmRequestData.value.forEach((item) => {
            let itemVal = item.value
            if (/#{.*?}/g.test(itemVal)) {
              // 变量解析
              // console.log('注入自定义参数-变量解析', )
              itemVal = replaseRegVariable(itemVal, this.info.data.formData)
            }
            // if (/{[^#{]+}/g.test(itemVal)) {
            //   //获取索引
            //   const index = itemVal.indexOf('}')
            //   //获取字段
            //   const field = itemVal.substring(2, index) + itemVal.substring(index + 1)
            //   //赋值
            //   itemVal = this.dataSorce[field]
            // }
            _data[item.key] = processingConstant(this, itemVal)
          })
        }
        console.log('_data', _data)
        formData.append('data', JSON.stringify({ ...this.info.data.formData, ..._data }))
        formData.append('method', this.info.extension?.method?.value)
        this.requestList = formData
      },
      async uploader(cb) {
        console.log('this.requestList----------', this.requestList)
        request({
          url: GFCD('dams', 'domain') + this.$store.getters['user/appCodeUrl'],
          method: 'post',
          data: this.requestList,
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          // responseType: 'blob',
        }).then((res) => {
          console.log('请你自己看看返回的啥', res)
          cb && cb(res)
        })
      },
      async uploader1(cb) {
        const result = []
        this.requestList.forEach((item) => {
          result.push(
            request({
              url: GFCD('dams', 'domain') + this.$store.getters['user/appCodeUrl'],
              method: 'post',
              data: item,
              headers: {
                'Content-Type': 'multipart/form-data',
              },
              // responseType: 'blob',
            })
          )
        })
        Promise.all(result).then((res) => {
          cb && cb(res)
          const failNumber = res.filter((item) => item.code !== '00000').length
          if (result.length === failNumber) {
            Toast('上传失败,请重试')
            return
          } else {
            Toast('上传成功')
          }
        })
      },
    },
  })
</script>
<style scoped>
  .preview-cover {
    position: absolute;
    bottom: 0;
    box-sizing: border-box;
    width: 100%;
    padding: 4px;
    color: #fff;
    font-size: 12px;
    text-align: center;
    background: rgba(0, 0, 0, 0.3);
  }
</style>
